<template>
	<view style="width: 100%;">

		<view class="filesBox" v-if="fileList.length > 0">
			<u-cell-group>
				<u-cell-item :title-style='titleStyle' title-width='500' :arrow="false" icon="file-text" :title="item.name" v-for="(item,index) in fileList"
				 :key='index'>
					<u-icon slot="right-icon" size="32" name="close" @click="delUpFile(index)"></u-icon>
				</u-cell-item>
			</u-cell-group>
		</view>
		<view class="addBox" ref="input">
			<view class="uploadtitle">
				点击选择文件
			</view>
		</view>
	</view>
</template>

<script>
	import {
		baseURL,
		baseImgUrl,
		Appid
	} from '@/config/config.js'
	export default {
		props: {
			defaultUrls: ''
		},
		watch: {
			defaultUrls(newVal, oldval) {

				if (newVal) {
					let files = newVal.split(',')
					if (files.length != 0 && this.fileList.length == 0) {
						files.forEach(item => {
							const newItem = item.split('/')
							const fileObj = {
								name: newItem[newItem.length - 1],
								url: item
							}
							this.fileList.push(fileObj);
						})
					}

				}
			}
		},
		data() {
			return {
				fileList: [],
				titleStyle: {
					whiteSpace: 'nowrap',
					textOverflow: 'ellipsis',
					overflow: 'hidden',
					wordBreak: 'break-all'
				}
			};
		},
		mounted() {
			this.$nextTick(function() {
				var input = document.createElement('input')
				input.style.width = "100%";
				input.type = 'file' //添加file类型
				input.multiple = 'multiple' // 可以选择多个
				// input.accept=".pdf" // 限制只能上传PDF文件，可以不限制，能上传任何类型
				input.style.height = "100%";
				input.style.position = "absolute";
				input.style.top = "0";
				input.style.right = "0";
				input.style.opacity = "0";
				input.style.overflow = "hidden"; //防止注意input 元素溢出
				input.id = 'file';
				var _this = this;
				setTimeout(() => {
					this.$refs.input.$el.appendChild(input); // 这里可能会报$el找不到错误，所以加了延时器，报错的原因是this.$refs.input没有找到为null，所以需要等页面结构加载完后再将其添加进去
					input.onchange = (event) => { // 点击上传选择文件
						var file = event.target.files;
						if (file.length > 0) {
							// 因为后台限制，只能一个一个文件的上传，所以当选择多个文件后，需要遍历一个一个调用上传接口
							for (let i = 0; i < file.length; i++) {
								let item = file[i]
								_this.uploadAPI(item); // 上传图片 
							}

						}
					}
				}, 1000)
			})
		},
		methods: {
			delUpFile(itemIndex) {
				this.fileList = this.fileList.filter((item, index) => index !== itemIndex)
				this.$emit('handSuccessFilsList', this.fileList)
			},
			uploadAPI(path) {
				uni.showLoading({
					title: '上传中'
				})
				var _this = this
				var fData = new FormData();
				fData.append("file", path);
				fData.append("moduleName", 'reports');
				var xhr = new XMLHttpRequest();
				var surl = baseURL + '/wechatMini/auth/commen/' + Appid + '/upload';
				xhr.open("POST", surl, true);
				xhr.onload = function(e) {
					// console.log("上传成功",e); //上传成功
				};
				xhr.onreadystatechange = () => {

					if (xhr.readyState == 4 && xhr.status == 200) { //上传后台成功
						uni.hideLoading()
						var res = JSON.parse(xhr.responseText)
						console.log(res, ';xhrxhrxhr')
						if (res.code == '405') {
								this.cache.removeCache('token')
								this.cache.removeCache('nickName')
								
							uni.showToast({
								title: '请登录后继续操作',
								icon: 'none'
							})
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/login/login',
									fail: (err) => {
										console.log(err)
									}
								})
							}, 2000)
						} else if (res.code == 200) {
							if (res.data) {
								const fileNameList = res.data.split('/')
								const fileObj = {
									name: fileNameList[fileNameList.length - 1],
									url: res.data
								}
								_this.fileList.push(fileObj); // 上传成功后放进fileList数组用于展示
								this.$emit('handSuccessFilsList', _this.fileList)
							}
						} else {
							uni.showToast({
								title: '发生未知错误，请稍微再试',
								icon: 'none'
							})
							this.$refs.upPositive.clear()
						}

					} else {
						uni.hideLoading()
					}
				}
				// 这里设置请求头，做的时候遇到一个问题，明明上传的是FormData，可是在请求中变成了request payload,后台需要的是FormData，解决方法，设置enctype为multipart/form-data，不要设置Content-Type，切记直接不设置Content-Type
				xhr.setRequestHeader('enctype', "multipart/form-data");
				xhr.setRequestHeader('MyToken', this.cache.getCache('token'));
				xhr.send(fData)
			},
		}
	}
</script>

<style lang="scss" scoped>
	.addBox {
		width: 100px;
		height: 60rpx;
		text-align: center;
		position: relative;
		margin: 0 auto;
		border-radius: 8rpx;
		border-color: #2979ff;
		color: #fff;
		line-height: 60rpx;
		background-color: #2979ff;
	}

	.uploadtitle {
		position: absolute;
		left: 0;
		right: 0;
	}

	.filesBox {
		margin-bottom: 30rpx;

		.u-cell {
			padding: 16rpx 0;
		}
	}
</style>
